#include "sync.h"
#include <QCryptographicHash>

void Sync::compare(QStringList &roots, QStringList &sourceFileList, QStringList &destinationFileList, QStringList &inputFileList)
{
    QVector<QByteArray> sourceFileMd5Vector, destinationFileMd5Vector;
    QFile file;
    QByteArray fileData;
    int srcIndex, dstIndex;
    bool flag = true;

    sourceFileMd5Vector.reserve(sourceFileList.count() / 2);
    for (srcIndex = 0; srcIndex < sourceFileList.count() / 2; srcIndex++) {
        sourceFileMd5Vector.push_back(md5ForFileName(roots[0] + sourceFileList[srcIndex * 2]));
    }
    destinationFileMd5Vector.reserve(destinationFileList.count() / 2);
    for (int dstIndex = 0; dstIndex < destinationFileList.count() / 2; dstIndex++) {
        destinationFileMd5Vector.push_back(md5ForFileName(roots[1] + destinationFileList[dstIndex * 2]));
    }
    for (dstIndex = 0; dstIndex < destinationFileList.count() / 2; dstIndex++) {
        flag = true;
        for (srcIndex = 0; srcIndex < sourceFileList.count() / 2; srcIndex++) {
            if (!destinationFileList[dstIndex * 2].compare(sourceFileList[srcIndex * 2])) {
                flag = false;
                break;
            } else {
                if (!destinationFileList[dstIndex * 2 + 1].compare(sourceFileList[srcIndex * 2 + 1])) {
                    if (destinationFileMd5Vector[dstIndex] == sourceFileMd5Vector[srcIndex]) {
                        flag = false;
                        break;
                    }
                }
            }
        }
        if (flag) {
            inputFileList.append(destinationFileList[dstIndex * 2]);
        }
    }
}

QByteArray Sync::md5ForFileName(const QString fileName)
{
    QFile file;
    QByteArray byteArray;

    file.setFileName(fileName);
    if (file.open(QIODevice::ReadOnly))
    {
        byteArray = file.readAll();
        byteArray = QCryptographicHash::hash( byteArray, QCryptographicHash::Md5);
    }
    file.close();

    return byteArray;
}

QTreeView* Sync::getSourceTreeView()
{
    return sourceTreeView;
}

void Sync::setSourceTreeView(QTreeView *newSourceTreeView)
{
    sourceTreeView = newSourceTreeView;
}

QTreeView* Sync::getDestinationTreeView()
{
    return destinationTreeView;
}

void Sync::setDestinationTreeView(QTreeView *newDestinationTreeView)
{
    destinationTreeView = newDestinationTreeView;
}

QTextEdit* Sync::getLogTextEdit()
{
    return logTextEdit;
}

void Sync::setLogTextEdit(QTextEdit *newLogTextEdit)
{
    logTextEdit = newLogTextEdit;
}
